package com.jsnu.xiaochi.controller;
import com.jsnu.xiaochi.pojo.User;
import com.jsnu.xiaochi.vo.Json;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;


@RestController
@RequestMapping("/user")
public class UserController {

    @PostMapping("/login")
    public Json login(String username, String password, HttpSession session){
        System.out.println(username+" "+password);
        String oper = "user login";
        Subject currentUser = SecurityUtils.getSubject();

        try {
            //登录
            currentUser.login( new UsernamePasswordToken(username, password) );
            //从session取出用户信息
            User user = (User) currentUser.getPrincipal();
            session.setAttribute("user",user);
            System.out.println("controller:"+user);
            if (user==null) throw new AuthenticationException();
            //返回登录用户的信息给前台，含用户的所有角色和权限
            return Json.succ(oper)
                    .data("username",user.getUsername())
                    .data("sex",user.getSex())
                    .data("roles",user.getRoles())
                    .data("perms",user.getPerms());

        } catch ( UnknownAccountException uae ) {
            return Json.fail(oper,"用户不存在");

        } catch ( IncorrectCredentialsException ice ) {
            return Json.fail(oper,"用户密码不正确");

        } catch ( LockedAccountException lae ) {
            return Json.fail(oper,"用户帐号被锁定不可用");

        } catch ( AuthenticationException ae ) {
            return Json.fail(oper,"登录失败："+ae.getMessage());
        }

    }


}
